package cn.edu.jnu.booklistmainactivity;

import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Objects;

import cn.edu.jnu.booklistmainactivity.data.BookItem;
import cn.edu.jnu.booklistmainactivity.data.DataSaver;

public class MainActivity extends AppCompatActivity {
    public static final int MENU_ID_ADD = 1;
    public static final int MENU_ID_UPDATE = 2;
    public static final int MENU_ID_DELETE = 3;
    private ArrayList<BookItem> shopItems;
    private MainRecycleViewAdapter mainRecycleViewAdapter;
    private RecyclerView recyclerViewMain;
    private ArrayList<BookItem> filterBook;
    public static ArrayList<Bookshelf>bookshelves=new ArrayList<>();
    private final ArrayList<BookItem> book_list_add= new ArrayList<>();
    private final ArrayList<BookItem> book_list2= new ArrayList<>();//第二个书架,先这样模拟的
    private final ArrayList<BookItem> book_list3= new ArrayList<>();//第三个书架
    private int Index=0;//记录用户选择了哪项(toolbar的sorted的时候)，全局变量


    private final ActivityResultLauncher<Intent> addDataLauncher= registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            ,result -> {
                if(null!=result){
                    Intent intent=result.getData();
                    if(result.getResultCode()==InputShopItemActivity.RESULT_CODE_SUCCESS)
                    {
                        assert intent != null;
                        Bundle bundle=intent.getExtras();
                        int position=bundle.getInt("position");//接收第二个界面的回传的位置信息(先由第一个页面传过去的)
                        BookItem add_book=(BookItem) bundle.getSerializable("book");
                        shopItems.add(position,add_book);
                        new DataSaver().Save(this,shopItems);
                        mainRecycleViewAdapter.notifyItemInserted(position);
                    }
                }
            });
    private final ActivityResultLauncher<Intent> updateDataLauncher= registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            ,result -> {
                if(null!=result){
                    Intent intent=result.getData();
                    if(result.getResultCode()==InputShopItemActivity.RESULT_CODE_SUCCESS)
                    {
                        assert intent != null;
                        Bundle bundle=intent.getExtras();
                        int position=bundle.getInt("position");//得到返回的位置
                        BookItem update_book=(BookItem) bundle.getSerializable("book");
                        shopItems.get(position).setBook(update_book);
                        new DataSaver().Save(this,shopItems);
                        mainRecycleViewAdapter.notifyItemChanged(position);
                    }
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainz);
        recyclerViewMain = findViewById(R.id.recycle_view_books);
        set_navmenu_toolbar();

        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerViewMain.setLayoutManager(linearLayoutManager);
        DataSaver dataSaver=new DataSaver();
        shopItems=dataSaver.Load(this);
        BookItem book1 = new BookItem("软件项目管理案例教程（第4版）", R.drawable.book_2,
                "韩万江 姜立新", "2019", "9", "韩万江 姜立新",
                " 机械工业出版社", "9787111629207");
        BookItem book2 = new BookItem("创新工程实践", R.drawable.book_1,
                "未知", "0000", "00", "未知",
                "未知", "000000");
        BookItem book3 = new BookItem("傲慢与偏见", R.drawable.pride_and_prejudice,
                "王科一", "2022", "5", "[英] 简·奥斯丁 ",
                "江苏凤凰文艺出版社", " 9787559459497");
        BookItem book4 = new BookItem("百年孤独", R.drawable.one_hundred_years_of_solitude,
                "范晔", "2011", "6", "[哥伦比亚] 加西亚·马尔克斯",
                "南海出版公司", " 9787544253994");
        BookItem book5 = new BookItem("解忧杂货店", R.drawable.miraclesin_namiyas_grocery,
                " 李盈春", "2020", "9", "[日] 东野圭吾",
                "南海出版公司", " 9787544298995");
        BookItem book6 = new BookItem("汇编语言", R.drawable.assembly_language,
                " 王爽", "2020", "1", "[中]王爽",
                "清华大学出版社", "9787302539414");
        if(shopItems.size()==0) {
            shopItems.add(book1);
            shopItems.add(book2);
            shopItems.add(book3);
            shopItems.add(book4);
            shopItems.add(book5);
            shopItems.add(book6);
        }
        Bookshelf bookshelf1 = new Bookshelf(shopItems);
        bookshelf1.setBookshelf_name("All");//默认都放在all
        bookshelves.add(bookshelf1);
        book_list2.add(0, book1);
        book_list2.add(1, book2);
        book_list2.add(2, book3);
        book_list2.add(3, book4);



        book_list3.add(0, book5);
        book_list3.add(1, book6);
        Bookshelf bookshelf2 = new Bookshelf(book_list2);
        bookshelf2.setBookshelf_name("书架1");

        Bookshelf bookshelf3 = new Bookshelf(book_list3);
        bookshelf3.setBookshelf_name("书架2");
        bookshelves.add(bookshelf2);
        bookshelves.add(bookshelf3);

        mainRecycleViewAdapter= new MainRecycleViewAdapter(shopItems);
        recyclerViewMain.setAdapter(mainRecycleViewAdapter);
        Button add_button = findViewById(R.id.button_add);
        add_button.setOnClickListener(v -> {
            Intent intent =new Intent(MainActivity.this,InputShopItemActivity.class);
            intent.putExtra("position",shopItems.size());
            BookItem temp_book=new BookItem();
            intent.putExtra("book",temp_book);
            addDataLauncher.launch(intent);
        });
        setBookShelf_Spinner();

    }


    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId())
        {
            case MENU_ID_ADD:
                Intent intent=new Intent(this, InputShopItemActivity.class);
                intent.putExtra("position",item.getOrder());
                BookItem temp_book=new BookItem();
                intent.putExtra("book",temp_book);
                addDataLauncher.launch(intent);
                break;
            case MENU_ID_UPDATE:
                Intent intentUpdate=new Intent(this, InputShopItemActivity.class);
                intentUpdate.putExtra("position",item.getOrder());
                intentUpdate.putExtra("book",shopItems.get(item.getOrder()));
                updateDataLauncher.launch(intentUpdate);
                break;
            case MENU_ID_DELETE:
                AlertDialog alertDialog;
                alertDialog = new AlertDialog.Builder(this)
                        .setTitle(R.string.confirmation)
                        .setMessage(R.string.sure_to_delete)
                        .setPositiveButton(R.string.yes, (dialogInterface, i) -> {
                            shopItems.remove(item.getOrder());
                            new DataSaver().Save(MainActivity.this,shopItems);
                            mainRecycleViewAdapter.notifyItemRemoved(item.getOrder());
                        }).setNegativeButton(R.string.no, (dialogInterface, i) -> {

                        }).create();
                alertDialog.show();
                break;

        }
        return super.onContextItemSelected(item);
    }
    @SuppressLint("NotifyDataSetChanged")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater=getMenuInflater();//实例化一个MenuInflater对象
        inflater.inflate(R.menu.toolbar,menu);//解析菜单文件,即是把toolbar布局给menu,然后下面menu就可以获取到mSearchitem

        //searchview setting
        final MenuItem mSearchitem=menu.findItem(R.id.tool_bar_search);
        SearchView msearchView=(SearchView) mSearchitem.getActionView();
        msearchView.setQueryHint("Search,输入关键词");
        msearchView.setSubmitButtonEnabled(true);//显示提交按钮，而不是需要按回车
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        msearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        msearchView.setOnCloseListener(() -> {
            Toast.makeText(MainActivity.this, "关闭", Toast.LENGTH_SHORT).show();
            recyclerViewMain.setAdapter(mainRecycleViewAdapter);//重新设置适配器
            mainRecycleViewAdapter.notifyDataSetChanged();
            return false;//如果是true，会导致关闭不了..
        });
        msearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public boolean onQueryTextChange(String newText) {//每次修改的文本在newtext
                filterBook=filter(newText);

                SearchAdapter searchAdapter=new SearchAdapter(filterBook,getApplicationContext());
                recyclerViewMain.setAdapter(searchAdapter);//更换成搜索适配器
                searchAdapter.notifyDataSetChanged();
                //设置点击事件
                searchAdapter.setitemlistener(position -> {//重写自定义接口的方法
                });
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }
    @SuppressLint({"NonConstantResourceId", "NotifyDataSetChanged"})
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.tool_bar_sorted:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setIcon(R.mipmap.ic_launcher)//不设置也行，源程序就没有设置这玩意
                        .setTitle("Sort By")
                        .setSingleChoiceItems(new String[]{"Title", "Author", "Publisher", "PubDate"}, Index, (dialog, which) -> Index = which)
                        .setPositiveButton("确定", (dialog, which) -> {
                            sortBook();
                            mainRecycleViewAdapter.notifyDataSetChanged();
                            dialog.dismiss();
                        })
                        .setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
                AlertDialog ad = builder.create();
                ad.show();
                break;
            case R.id.tool_bar_search:
                Toast.makeText(this, "搜索", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    @SuppressLint("NonConstantResourceId")
    private void set_navmenu_toolbar() {//设置toolbar和抽屉菜单
        DrawerLayout mDrawerLayout = findViewById(R.id.main_activity_drawerLayout);
        Toolbar mToolbar = findViewById(R.id.main_activity_toolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_baseline_menu_24);
        setSupportActionBar(mToolbar);//添加 Toolbar
        Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);//隐藏actionbar显示的标题
        //            或者直接open();
        mToolbar.setNavigationOnClickListener(pView -> {
            mDrawerLayout.openDrawer(GravityCompat.START);//点击后会打开抽屉菜单
        });
        //抽屉菜单
        NavigationView mnavView = findViewById(R.id.main_activity__nav_menu);
        mnavView.setCheckedItem(R.id.searchview);

        //设置headerlayout点击事件
        View mHeaderView = mnavView.getHeaderView(0);
        ImageView mIvHeaderImg = mHeaderView.findViewById(R.id.iv_nav_img);//获取头布局内 imageview 控件
        mIvHeaderImg.setOnClickListener(v -> Toast.makeText(MainActivity.this, "ImageView", Toast.LENGTH_LONG).show());
        mnavView.setNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.item_nav_menu_books:
                    Toast.makeText(MainActivity.this, "请返回主界面查看书籍信息", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.item_nav_menu_search:
                    Toast.makeText(MainActivity.this, "请返回主页面搜索", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.item_nav_menu_setting:
                    Toast.makeText(MainActivity.this, "设置", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(MainActivity.this, setting_Activity.class));
                    break;
                case R.id.item_nav_menu_about:
                    Toast.makeText(MainActivity.this, "关于", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(MainActivity.this, about_Activity.class));
                    break;
                default:
                    Toast.makeText(MainActivity.this, "default", Toast.LENGTH_SHORT).show();
                    break;
            }
            mDrawerLayout.closeDrawers();
            return true;
        });
    }
    private void setBookShelf_Spinner(){
        Spinner bookshelf_spinner=findViewById(R.id.main_activity_spinner);
        ArrayAdapter<Bookshelf> bookshelfArrayAdapter=new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,bookshelves);
        bookshelfArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        Bookshelf addNewShelf = new Bookshelf(book_list_add);
        bookshelfArrayAdapter.add(addNewShelf);
        addNewShelf.setBookshelf_name("添加新书架");
        bookshelf_spinner.setAdapter(bookshelfArrayAdapter);
        bookshelf_spinner.setSelection(0);
        bookshelf_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Bookshelf bookshelf_selected=(Bookshelf) bookshelf_spinner.getSelectedItem();

                if(("添加新书架"+"("+bookshelf_selected.getBookshelf_List().size()+")").equals(bookshelf_selected.toString())){
                    Toast.makeText(MainActivity.this, "添加新书架", Toast.LENGTH_SHORT).show();
                }
                else{
                    mainRecycleViewAdapter.setBook_list(bookshelf_selected.getBookshelf_List());
                    mainRecycleViewAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    public static class MainRecycleViewAdapter extends RecyclerView.Adapter<MainRecycleViewAdapter.ViewHolder> {

        private ArrayList<BookItem> localDataSet;
        /**
         * Provide a reference to the type of views that you are using
         * (custom ViewHolder).
         */
        public void setBook_list(ArrayList<BookItem> book_list){
            this.localDataSet=book_list;
        }
        public ArrayList<BookItem> getBook_list(){
            return this.localDataSet;
        }
        public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            private final ImageView image;
            private final TextView title;
            private final TextView writername;
            private final TextView publishhouse;
            private final TextView yeartime;
            private final TextView monthtime;

            public ViewHolder(View view) {
                super(view);
                // Define click listener for the ViewHolder's View

                image=view.findViewById(R.id.image_view_book_cover);//赋值,上下移动的时候item项应该会自动来这样子调用修改
                title=view.findViewById(R.id.text_view_book_title);
                writername=view.findViewById(R.id.text_view_book_writer);
                publishhouse=view.findViewById(R.id.text_view_book_publish_house);
                yeartime=view.findViewById((R.id.text_view_book_yeartime));
                monthtime=view.findViewById(R.id.text_view_book_monthtime);

                view.setOnCreateContextMenuListener(this);
            }

            public TextView getTextView() {
                return title;
            }//因为这些是私有成员，所以需要提供一个外界可以获取的方法
            public ImageView getImageViewImage() {
                return image;
            }
            public TextView getWritername() {return writername;}
            public TextView getPublishhouse() {return publishhouse;}
            public TextView getyearTime() {return yeartime;}
            public TextView getMonthtime() {
                return monthtime;
            }
            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                contextMenu.add(0, MENU_ID_ADD,getAdapterPosition(), "添加 "+ getAdapterPosition() );
                contextMenu.add(0, MENU_ID_UPDATE, getAdapterPosition(), "更新 " + getAdapterPosition());
                contextMenu.add(0, MENU_ID_DELETE, getAdapterPosition(), "删除 " + getAdapterPosition());
            }
        }


        public MainRecycleViewAdapter(ArrayList<BookItem> dataSet) {
            localDataSet = dataSet;
        }

        // Create new views (invoked by the layout manager)
        @Override
        @NonNull
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            // Create a new view, which defines the UI of the list item
            View view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.bookitem, viewGroup, false);

            return new ViewHolder(view);
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override

        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            viewHolder.getImageViewImage().setBackgroundResource(localDataSet.get(position).getImageId());//设置图片用setbackground/imagesource
            viewHolder.getTextView().setText(localDataSet.get(position).getBookName());//不能用[position],因为这是列表，不是数组
            viewHolder.getWritername().setText(localDataSet.get(position).getWriterName());
            viewHolder.getPublishhouse().setText(localDataSet.get(position).getPublishingHouse());
            viewHolder.getyearTime().setText(localDataSet.get(position).getPublishyear());
            viewHolder.getMonthtime().setText(localDataSet.get(position).getPublishmonth());
        }
        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return localDataSet.size();
        }

    }
    private ArrayList<BookItem>filter(String text){
        filterBook = new ArrayList<>();
        for (BookItem book: mainRecycleViewAdapter.getBook_list()){
            if (book.getBookName().contains(text)) {
                filterBook.add(book);
            }
            else if (book.getPublishyear().contains(text)) {
                filterBook.add(book);
            }
            else if (book.getPublishingHouse().contains(text)) {
                filterBook.add(book);
            }
            else if (book.getWriterName().contains(text)) {
                filterBook.add(book);
            }
            else if (book.getPublishmonth().contains(text)) {
                filterBook.add(book);
            }
        }
        return filterBook;
    }
    private void sortBook(){
        Comparator<BookItem> comparator;
        switch (Index){
            case 0:
                comparator =new BookItem.BookNameComparator();
                break;
            case 1:
                comparator =new BookItem.WriterNameComparator();
                break;
            case 2:
                comparator =new BookItem.PublishHouseComparator();
                break;
            case 3:
                comparator =new BookItem.PubTimeComparator();
                break;
            default:
                comparator =new BookItem.PubTimeComparator();;
        }
        Collections.sort(mainRecycleViewAdapter.getBook_list(), comparator);
    }
}